package com.beta.cust.bind.datasync.job;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.beta.cat.service.RedissonService;
import com.beta.cat.utils.JsonUtil;
import com.beta.cat.utils.ReflectUtils;
import com.beta.cust.bind.api.model.CrmCustDetailEntity;
import com.beta.cust.bind.api.service.IRpcCustService;
import com.beta.cust.bind.datasync.config.CfgSelfRefreshBean;
import com.beta.cust.bind.datasync.constant.BusinessConstant;
import com.beta.cust.bind.datasync.constant.RedisConstant;
import com.beta.cust.bind.datasync.constant.ResultCode;
import com.beta.cust.bind.datasync.dto.CrmCustDetailReq;
import com.beta.cust.bind.datasync.mapper.entity.CrmCustDetail;
import com.beta.cust.bind.datasync.service.ICrmCustDetailService;
import com.beta.elephant.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

/**
 * @Auther: pcc
 * @Date: 2024/4/3 09:37
 * @Description:
 */
@Slf4j
@Component
public class SyncCrmTask {

    @Autowired
    private ICrmCustDetailService crmCustDetailService;

    @DubboReference
    private IRpcCustService rpcCustService;

    @Autowired
    private CfgSelfRefreshBean cfgSelfRefreshBean;

    @Autowired
    private RedissonService redissonService;

    /**
     * 定时同步获取crmCustDetail信息
     * <p>
     * 1、分页查询crmCustDetail表
     * 2、调用对应的行方接口获取最新信息
     * 3、更新最新信息到本地
     */
    @Scheduled(cron = "0 0 */2 * * ?")
    public void syncCrmCustDetailTask() {
        log.info("syncCrmCustDetailTask start");
        if(cfgSelfRefreshBean.getCrmTaskOpen().equals("false")){
            log.warn("crm sync close!!!");
            return ;
        }
        long startTime = System.currentTimeMillis();
        String lockKey = String.format(RedisConstant.SYNC_CRM_DETAIL_LOCK_KEY);
        try {
            if (!redissonService.tryLock(lockKey, RedisConstant.WAIT_TIME_ZERO)) {
                log.error("syncCrmCustDetailTask is running");
                return;
            }
            //1、分页查询crmCustDetail表
            CrmCustDetailReq req = new CrmCustDetailReq();
            req.setPageSize(BusinessConstant.DEFAULT_PAGE_SIZE);
            while (true) {
                IPage<CrmCustDetail> page = crmCustDetailService.selectPage(req);
                if (CollectionUtils.isEmpty(page.getRecords())) {
                    return;
                }
                req.setId(page.getRecords().get(page.getRecords().size() - 1).getId());//将最后一个id作为条件
                for (CrmCustDetail crmCustDetail : page.getRecords()) {
                    //2、调用对应的行方接口获取最新信息
                    ResultVO<CrmCustDetailEntity> crmResp = rpcCustService.queryCrmCustDetail(crmCustDetail.getPhone(), crmCustDetail.getCustManagerPhone());
                    if (crmResp.getCode() != ResultCode.SUCCESS.getCode() || null == crmResp.getData()) {
                        log.error("syncCrmCustDetailTask-queryCrmCustDetail result {},custPhone:{},managerPhone:{}", JsonUtil.toJson(crmResp), crmCustDetail.getPhone(), crmCustDetail.getCustManagerPhone());
                        continue;
                    }
                    //3、更新最新信息到本地
                    BeanUtils.copyProperties(crmResp.getData(),crmCustDetail);
                    crmCustDetailService.updateById(crmCustDetail);
                }
            }
        }finally {
            log.warn("syncCrmCustDetailTask end costs:{}ms", System.currentTimeMillis() - startTime);
            redissonService.unlock(lockKey);
        }
    }

}
